// main
const fs = require('fs')
const path = require('path')

// utils
const ora = require('ora')
const chalk = require('chalk')

/**
 * create 命令，接收一个config文件夹下配置项的文件名。根据配置创建一个项目
 */
const { program } = require('commander')
program.name('create util').description('create a project by config file').version('0.0.1')
program
	.command('create')
	.description('pass config file to create a project')
	.argument('<string>', 'config file name')
	.action((name, options) => {
		createPrj(name, options)
	})
program.parse()

/**
 * create project by config
 * @param {string} name file name
 * @param {object} options command otions
 */
function createPrj(confName, options = {}) {
	const spinner = ora(chalk.cyan('开始创建项目'))
	spinner.start()

	const conf = require(path.resolve(__dirname, 'config', confName)) // 新项目配置

	const distDir = path.resolve(__dirname, 'project', path.basename(confName, '.json')) // 新项目根目录
	const srcFile = conf.file // 新项目目标文件

	if (fs.existsSync(distDir)) fs.rmdirSync(distDir, { recursive: true }) // 判断项目根目录是否已存在
	fs.mkdirSync(distDir, { recursive: true })

	// 开始读取输入目录的文件，根据配置文件过滤项目中需要的目录
	const ENTRY = path.resolve(__dirname, 'src')
	fs.readdir(ENTRY, { withFileTypes: true }, (err, files) => {
		if (err) {
			console.log(chalk.bgRed('读取文件失败'))
			process.exit(1)
		}
		// 需要的文件
		const _needFile = files.filter((f) => srcFile.includes(f.name))
		console.log('_needFile: ', _needFile)

		fs.readdir(path.resolve(__dirname, 'src', 'options.js'), { withFileTypes: true }, (err, files) => {
			console.log('===========', files, err)
		})

		files.forEach((file) => {
			if (srcFile.includes(file.name)) {
				//判断是否为文件夹
				if (file.isDirectory()) {
					const dirS = path.resolve(ENTRY, file.name)
					const dirD = path.resolve(distDir, file.name)
					//判断是否存在dirD文件夹
					if (!fs.existsSync(dirD)) {
						fs.mkdir(dirD, (err) => {
							if (err) console.log(err)
						})
					}
					copyDir(dirS, dirD)
				} else {
					const srcFile = path.resolve(ENTRY, file.name)
					const desFile = path.resolve(distDir, file.name)
					fs.copyFileSync(srcFile, desFile)
					console.log('\n文件拷贝完成: ', file.name)
				}
			}
		})
		console.log('拷贝结束')
	})

	spinner.stop()
}

function copyDir(srcDir, desDir) {
	fs.readdir(srcDir, { withFileTypes: true }, (err, files) => {
		if (err) {
			console.log(chalk.bgRed('读取文件失败'))
			process.exit(1)
		}
		files.forEach((file) => {
			//判断是否为文件夹
			if (file.isDirectory()) {
				const dirS = path.resolve(srcDir, file.name)
				const dirD = path.resolve(desDir, file.name)
				//判断是否存在dirD文件夹
				if (!fs.existsSync(dirD)) {
					fs.mkdir(dirD, (err) => {
						if (err) console.log(err)
					})
				}
				copyDir(dirS, dirD)
			} else {
				const srcFile = path.resolve(srcDir, file.name)
				const desFile = path.resolve(desDir, file.name)
				fs.copyFileSync(srcFile, desFile)
				console.log('\n文件拷贝完成: ', file.name)
			}
		})
	})
}
